﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MinistryStandardPlatformEntity;
using MinistryStandardPlatformWeb;
using Webdiyer.WebControls.Mvc;

namespace MinistryStandardPlatformWeb.Controllers
{
    [IsLogin]
    public class TowerController : Controller
    {
        //
        // GET: /Tower/
        private MSPDataContext context = new MSPDataContext();

        [MenuAuthorized("14")]
        public ActionResult Index()
        {
            var towers = from t in context.InfoTower
                         orderby t.InsertTime descending
                         select t;

            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                string id = HttpUtility.UrlDecode(Request.QueryString["id"]);
                towers = from t in towers
                         where t.ParentUnitID == id
                         orderby t.InsertTime descending
                         select t;

            }

            return PartialView(towers.ToPagedList(1, CommonDictionary.PageSize));
        }

        [MenuAuthorized("144")]
        public ActionResult Data(string condition, string unitId, string searchAll, int pageIndex = 1)
        {
            var towers = from t in context.InfoTower
                          orderby t.InsertTime descending
                          select t;
            if (!string.IsNullOrEmpty(unitId) && searchAll != "on")
            {
                towers = from t in towers
                          where t.ParentUnitID == unitId
                          orderby t.InsertTime descending
                          select t;

            }
            if (!string.IsNullOrEmpty(unitId) && searchAll == "on")
            {
                List<string> ids = CommonFunctions.GetAllChildrenUnits(unitId, CommonFunctions.GetLoginUser().UserId);
                ids.Add(unitId);
                towers = from r in towers
                         where ids.Contains(r.ParentUnitID)
                         orderby r.ParentUnitID, r.InsertTime descending
                         select r;
            }
            if (!string.IsNullOrEmpty(condition))
            {
                towers = from t in towers
                          where t.TowerName.Contains(condition)
                          orderby t.InsertTime descending
                          select t;

            }
            return PartialView(towers.ToPagedList(pageIndex, CommonDictionary.PageSize));
        }

        [MenuAuthorized("141")]
        public ActionResult Create()
        {
            string unitId = HttpUtility.UrlDecode(Request.QueryString["unitId"]);
            string unitName = HttpUtility.UrlDecode(Request.QueryString["unitName"]);
            return View(new InfoTower()
                {
                    ParentUnitID = unitId,
                    ParentUnitName = unitName,
                    InfoUnit = new InfoUnit()
                    {
                        UNITID = unitId,
                        UNITNAME = unitName
                    }
                });
        }

        [HttpPost]
        [MenuAuthorized("141")]
        public ActionResult Create(InfoTower tower)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    tower.Towerid = "TOWE" + CommonFunctions.GetDateTimeStrAnd4BitsRandom();
                    tower.InsertTime = DateTime.Now;
                    tower.InUserID = CommonFunctions.GetLoginUser().UserId;
                    context.InfoTower.InsertOnSubmit(tower);
                    context.SubmitChanges();
                    ViewBag.Message = "添加成功";
                }
                catch (System.Exception ex)
                {
                    ViewBag.Message = "添加失败," + ex.Message;
                }
            }
            else
            {
                ViewBag.Message = "添加失败";
            }
            return View(tower);
        }

        //选择塔楼的所属单位
        public ActionResult PickParentUnit()
        {
            var units = context.RightsDetails.Where(u => u.UserId == CommonFunctions.GetLoginUser().UserId && u.NodeTYPE == true).Select(u => new { NodeId = u.NodeId, ParentNodeId = u.ParentNodeId, NodeName = u.NodeName });
            List<ZTreeNode> nodes = new List<ZTreeNode>();
            foreach (var unit in units)
            {
                ZTreeNode node = new ZTreeNode();
                node.id = unit.NodeId;
                node.pId = unit.ParentNodeId;
                node.name = unit.NodeName;
                node.icon = "/Content/themes/zTreeStyle/img/diy/1_open.png";
                if (unit.ParentNodeId == null)
                {
                    node.open = true;
                }
                else
                {
                    node.open = false;
                }
                nodes.Add(node);
            }
            ViewBag.nodesJson = CommonFunctions.ListToJsonStr<ZTreeNode>(nodes);
            return View();
        }

        [MenuAuthorized("142")]
        public ActionResult Delete(string parameters)
        {
            var tower = context.InfoTower.SingleOrDefault(t => t.Towerid == parameters);

            try
            {
                context.InfoTower.DeleteOnSubmit(tower);
                context.SubmitChanges();
                return Json(new { success = true, message = "" });
            }
            catch (System.Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        [MenuAuthorized("143")]
        public ActionResult Edit(string id)
        {
            var tower = context.InfoTower.SingleOrDefault(t => t.Towerid == id);
            return View(tower);
        }

        [HttpPost]
        [MenuAuthorized("143")]
        public ActionResult Edit(FormCollection form)
        {
            try
            {
                var towerToUpdate = context.InfoTower.SingleOrDefault(t => t.Towerid == form["Towerid"]);
                UpdateModel(towerToUpdate, form.ToValueProvider());
                context.SubmitChanges();
                ViewBag.Message = "修改成功";

                return View(towerToUpdate);
            }

            catch (System.Exception ex)
            {
                ViewBag.Message = "修改失败," + ex.Message;
                return View(new InfoTower());

            }

        }
    }
}
